package model;

import controller.exceptions.InvalidVersionException;
import controller.exceptions.ItemAlreadyRemovedException;
import filesystem.Assistants;
import filesystem.exceptions.InvalidModelItemException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * The artist model class
 */
public class ArtistModel extends BaseModel implements Model {

    public ArtistModel() {
    }
    
    /**
     * Select items from the model by parametr
     *
     * @param parametr parametr of the search
     * @return list of the found objects
     */
    public ArrayList selectItems() throws IOException {
        getItems().clear();
        super.setItems(Assistants.arFA.getItems());
        return super.getItems();
    }

    public ArrayList selectItems(ModelItem parametr) throws IOException {
        getItems().clear();
        HashMap map = parametr.itemToMap();
        super.setItems(Assistants.arFA.getItems(map));
        return super.getItems();
    }
    
    /**
     * Edit object in the model
     *
     * @param item changing object
     */
    public void setItem(ModelItem item) throws InvalidModelItemException,
            IOException, InvalidVersionException, ItemAlreadyRemovedException {
        //ищем объект в загруженной модели
        int i = 0;
        Iterator it = getItems().iterator();
        ModelItem buf = null;
        while (it.hasNext()) {
            buf = (Artist) it.next();
            if (item.getId() == buf.getId()) {
                if (item.getVersion() != buf.getVersion()) {
                    throw new InvalidVersionException();
                }
                item.incrementVersion();
                getItems().set(i, item);
                break;
            }
            i++;
            if (!it.hasNext()) {
                throw new ItemAlreadyRemovedException();
            }
        }
        //сохраняем изменения
        Assistants.getFileAssistant(item).setItem(item);
        Assistants.tFA.resetLoaded();
    }
}
